import TextEditor from '@/pages/cues/components/TextEditor';
import { saveRecord } from '@/services/api/api-pressconference';
import { CheckCircleTwoTone, FileSearchOutlined, SendOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProForm,
  ProFormDateTimePicker,
  ProFormGroup,
  ProFormInstance,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Divider, message } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import { useAccess, useModel } from 'umi';
import UploadDragger from '../components/UploadDragger';
import AssignContact from './AssignContact';
interface AddRecordProps {
  onSave: () => void;
}

const AddRecord: React.FC<AddRecordProps> = ({ onSave }) => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  const verificationSubmit = (values: any) => {
    console.log('====', values);

    if (!(values.name !== undefined)) {
      message.warning('请输入标题');
      return false;
    }

    values.name = values.name.trim();

    if (!(values?.name.length > 0)) {
      message.warning('请输入标题');
      return false;
    }

    if (!(values.location !== undefined)) {
      message.warning('请输入地点');
      return false;
    }

    values.location = values.location.trim();

    if (!(values?.location.length > 0)) {
      message.warning('请输入地点');
      return false;
    }

    if (values.deadlineTime === undefined) {
      message.warning('请选择截止时间');
      return;
    }

    if (values?.startTime == undefined) {
      message.warning('请选择开始时间');
      return false;
    }

    if (values?.endTime == undefined) {
      message.warning('请选择结束时间');
      return false;
    }

    if (!(values?.problem?.length > 0)) {
      message.warning('请输入问题');
      return false;
    }

    return true;
  };

  return (
    <DrawerForm
      title="发布指令"
      trigger={
        <Button key="button" type="primary" icon={<SendOutlined />}>
          发布指令
        </Button>
      }
      layout="horizontal"
      formRef={formRef}
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        // forceRender: true,
        destroyOnClose: true,
        maskClosable: false,
        width: 1150,
        closable: true,
      }}
      initialValues={{
        assignType: '4',
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        searchConfig: {
          submitText: (
            <>
              <FileSearchOutlined /> 预览
            </>
          ),
        },
        render: (props, defaultDoms) => {
          return [
            defaultDoms,
            <Button
              key="button_add_submit"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                const values = formRef.current?.getFieldsValue();
                if (!verificationSubmit(values)) {
                  return;
                }
                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_add_submit'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: '30%',
                destroyOnClose: true,
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                props.submit();
                return true;
              }}
            >
              提交后，将自动推送指令！
            </ModalForm>,
          ];
        },
      }}
      onFinish={async (values) => {
        if (!verificationSubmit(values)) {
          return false;
        }

        let attachmentIds = [];

        console.log('===', values);

        if (values.attachments !== undefined && values.attachments.length > 0) {
          const attachments = values.attachments
            .filter((item: { status: string }) => {
              return item.status === 'done';
            })
            .map((item: { response: { data: { id: any } } }) => {
              return item.response.data.id;
            });

          attachmentIds = attachments;
        }

        if (values.startTime != undefined) {
          values.startTime = values.startTime + ':00';
        }

        if (values.endTime != undefined) {
          values.endTime = values.endTime + ':00';
        }

        const response = await saveRecord({
          name: values.name,
          location: values.location,
          deadlineTime: values.deadlineTime,
          startTime: values.startTime,
          endTime: values.endTime,
          assignCombineIds: values.assignCombineIds,
          problem: values.problem,
          content: values.content,
          attachmentIds: attachmentIds,
        });

        if (response.code === 0) {
          message.success('提交成功');
          onSave();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProFormTextArea
        width="xl"
        name="name"
        required
        label="主题"
        placeholder="请输入名称"
        fieldProps={{
          allowClear: true,
          rows: 2,
          maxLength: 200,
          showCount: true,
        }}
        rules={[{ required: true, message: '这是必填项' }]}
      />
      <ProFormDateTimePicker
        width="xl"
        name="deadlineTime"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            截止
          </>
        }
        extra="到达设定的截止时候后，系统会关闭该指令"
        fieldProps={{
          minDate: dayjs(),
          presets: [
            { label: '后3天', value: dayjs().add(3, 'd') },
            { label: '后5天', value: dayjs().add(5, 'd') },
            { label: '后7天', value: dayjs().add(7, 'd') },
            { label: '后10天', value: dayjs().add(10, 'd') },
            { label: '后15天', value: dayjs().add(15, 'd') },
            { label: '后20天', value: dayjs().add(20, 'd') },
            { label: '后30天', value: dayjs().add(30, 'd') },
            { label: '后50天', value: dayjs().add(50, 'd') },
            { label: '后90天', value: dayjs().add(90, 'd') },
          ],
          format: 'YYYY-MM-DD HH:mm:ss',
        }}
      />
      <ProFormGroup>
        <ProFormDateTimePicker
          name="startTime"
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              开始
            </>
          }
          fieldProps={{
            minDate: dayjs(),
            format: 'YYYY-MM-DD HH:mm',
          }}
          extra="新闻发布会预计开始与结束日期时间"
        />
        <ProFormDateTimePicker
          name="endTime"
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              结束
            </>
          }
          fieldProps={{
            minDate: dayjs(),
            format: 'YYYY-MM-DD HH:mm',
          }}
        />
      </ProFormGroup>
      <ProFormTextArea
        width="xl"
        name="location"
        required
        label="地点"
        placeholder="请输入地点"
        fieldProps={{
          allowClear: true,
          rows: 2,
          maxLength: 200,
          showCount: true,
        }}
        rules={[{ required: true, message: '这是必填项' }]}
      />
      {/* 联络人（多选） */}
      <AssignContact formRef={formRef} />
      <Divider />
      <ProForm.Item
        name="content"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            内容
          </>
        }
      >
        <TextEditor
          onInit={(editor) => {}}
          readonly={false}
          onClick={(value) => {}}
          defaultContent=""
          tinyID="tinyId"
        />
      </ProForm.Item>
      <ProFormTextArea
        width="xl"
        name="problem"
        required
        label="问题"
        placeholder="请输入问题"
        fieldProps={{
          allowClear: true,
          rows: 5,
          maxLength: 500,
          showCount: true,
        }}
        rules={[{ required: true, message: '这是必填项' }]}
      />

      <FormItem
        name="attachments"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            附件
          </span>
        }
        hidden={!access.新闻发布x配置x管理员}
      >
        <UploadDragger
          onPreview={(file) => {}}
          access={{
            isPicture: access.新闻发布x配置x管理员,
            isVideo: access.新闻发布x配置x管理员,
            isOffice: access.新闻发布x配置x管理员,
            isOther: access.新闻发布x配置x管理员,
          }}
          url="/pressconference/attachment/save"
        />
      </FormItem>
    </DrawerForm>
  );
};

export default AddRecord;
